// components/demo/index.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleReady: function ({ detail }) {
      this.scene = detail.value;
      const xrFrameSystem = wx.getXrFrameSystem();
      this.camera = this.scene.getElementById('camera').getComponent(xrFrameSystem.Camera);
      this.helmet = { el: this.scene.getElementById('helmet'), color: 'rgba(44, 44, 44, 0.5)' };
      this.miku = { el: this.scene.getElementById('miku'), color: 'rgba(44, 44, 44, 0.5)' };
      this.tmpV3 = new (xrFrameSystem.Vector3)();
    },
    handleTick: function ({ detail }) {
      this.helmet && this.triggerEvent('syncPositions', [
        this.getScreenPosition(this.helmet),
        this.getScreenPosition(this.miku)
      ]);
    },
    handleAssetsProgress: function ({ detail }) {
      this.triggerEvent('assetsLoaded', detail.value);
    },
    handleAssetsLoaded: function ({ detail }) {
      console.log('assets loaded', detail.value);
    },
    handleTouchModel: function ({ detail }) {
      const { target } = detail.value;
      this[target.id].color = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
    },
    getScreenPosition: function (value) {
      const { el, color } = value;
      const xrFrameSystem = wx.getXrFrameSystem();
      this.tmpV3.set(el.getComponent(xrFrameSystem.Transform).worldPosition);
      const clipPos = this.camera.convertWorldPositionToClip(this.tmpV3);
      const { frameWidth, frameHeight } = this.scene;
      return [((clipPos.x + 1) / 2) * frameWidth, (1 - (clipPos.y + 1) / 2) * frameHeight, color, el.id];
    }
  }
})